package org.cid54.bukkit.command;

import org.cid54.bukkit.command.util.PlayerCommand;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.event.player.PlayerChatEvent;
import org.cid54.bukkit.Cid54PlayerListener;
import org.cid54.bukkit.model.Cid54Gate;
import org.cid54.bukkit.model.GateDao;

/**
 *
 * @author Cid54
 */
public class TelePortCommand implements PlayerCommand {

    private GateDao gateDao = GateDao.instance;

    private void checkTargetLocation(Location loc) {

        World w = loc.getWorld();

        Location targetLoc = Cid54PlayerListener.cloneLocation(loc);

        w.getBlockAt(targetLoc).setType(Material.AIR);

        targetLoc.setY(targetLoc.getY() + 1D);

        w.getBlockAt(targetLoc).setType(Material.AIR);

    }

    public boolean execute(String command, PlayerChatEvent event, Cid54PlayerListener listener) {

        String[] commands = command.split(" ");

        if (commands.length == 2) {

            String gateName = commands[1].toLowerCase();

            Cid54Gate gate = this.gateDao.getGateByName(gateName);

            if (gate != null) {
                Location loc = new Location(event.getPlayer().getWorld(), gate.getX(), gate.getY(), gate.getZ());
                this.checkTargetLocation(loc);
                event.getPlayer().teleport(loc);
            }

            return true;
        }

        if (commands.length > 3) {

            int x = Integer.parseInt(commands[1]);
            int z = Integer.parseInt(commands[2]);
            int y = Integer.parseInt(commands[3]);

            Location loc = new Location(event.getPlayer().getWorld(), x, y, z);
            this.checkTargetLocation(loc);
            event.getPlayer().teleport(loc);

            return true;
        }

        return false;
    }

    public String getCommand() {
        return "tp";
    }

    public String getHelpText() {
        return "tp x z y | gateName";
    }
}
